// 控制器层 - 负责处理用户交互
class StudentController {
    constructor(model, view) {
        this.model = model;
        this.view = view;
        this.rollInterval = null;
        
        this.initEventListeners();
    }

    // 初始化事件监听器
    initEventListeners() {
        // 文件输入监听
        const fileInput = document.getElementById('fileInput');
        fileInput.addEventListener('change', (e) => this.handleFileImport(e));
    }

    // 导入学生名单
    importStudents() {
        const fileInput = document.getElementById('fileInput');
        fileInput.click();
    }

    // 处理文件导入
    handleFileImport(event) {
        const file = event.target.files[0];
        if (!file) return;

        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' });
                const students = this.model.parseExcelData(workbook.Sheets);
                
                if (students.length > 0) {
                    this.model.clearAllStudents();
                    this.model.addStudents(students);
                    this.updateViews();
                    alert(`成功导入 ${students.length} 名学生！`);
                } else {
                    alert('未能识别到有效的学生名单，请检查Excel文件格式。');
                }
            } catch (error) {
                console.error('文件解析错误:', error);
                alert('文件解析失败，请确保文件格式正确。');
            }
        };
        reader.readAsArrayBuffer(file);
        
        // 清空文件输入，允许重复选择同一文件
        event.target.value = '';
    }

    // 导出学生名单
    exportStudents() {
        const students = this.model.getAllStudents();
        if (students.length === 0) {
            alert('没有学生数据可以导出！');
            return;
        }

        try {
            const workbook = this.model.exportToExcel();
            const fileName = `学生名单_${new Date().toLocaleDateString()}.xlsx`;
            XLSX.writeFile(workbook, fileName);
            alert('学生名单导出成功！');
        } catch (error) {
            console.error('导出错误:', error);
            alert('导出失败，请重试。');
        }
    }

    // 开始点名
    startRoll() {
        const students = this.model.getAllStudents();
        if (students.length === 0) {
            alert('请先导入学生名单！');
            return;
        }

        this.model.setRollingState(true);
        this.view.updateButtonStates(true);
        this.view.startRollingAnimation();
        
        // 开始随机选择学生
        this.rollInterval = setInterval(() => {
            const randomStudent = this.model.getRandomStudent();
            this.model.setSelectedStudent(randomStudent);
        }, 100);
    }

    // 停止点名
    stopRoll() {
        if (!this.model.isCurrentlyRolling()) return;

        this.model.setRollingState(false);
        this.view.updateButtonStates(false);
        this.view.stopRollingAnimation();
        
        if (this.rollInterval) {
            clearInterval(this.rollInterval);
            this.rollInterval = null;
        }

        // 最终选择一个学生
        const finalStudent = this.model.getRandomStudent();
        this.model.setSelectedStudent(finalStudent);
        this.view.highlightStudent(finalStudent);
        this.view.updateSelectedStudent(finalStudent);
        
        // 播放选中效果
        this.playSelectionEffect();
    }

    // 重置点名
    resetRoll() {
        // 停止当前滚动
        if (this.model.isCurrentlyRolling()) {
            this.stopRoll();
        }
        
        // 重置模型状态
        this.model.setSelectedStudent(null);
        this.model.setRollingState(false);
        
        // 重置视图
        this.view.reset();
        this.view.updateButtonStates(false);
    }

    // 播放选中效果
    playSelectionEffect() {
        const selectedElement = document.getElementById('selectedStudent');
        selectedElement.style.animation = 'pulse 0.5s ease-in-out 3';
        
        setTimeout(() => {
            selectedElement.style.animation = '';
        }, 1500);
    }

    // 更新所有视图
    updateViews() {
        const students = this.model.getAllStudents();
        this.view.updateStudentNodes(students);
        this.view.updateStudentList(students);
    }

    // 手动添加学生（用于测试）
    addTestStudents() {
        const testStudents = [
            '张明轩', '李思雨', '王浩然', '赵雅琪', '陈志强', '刘美琳', '杨俊杰', '黄诗涵',
            '周天宇', '吴梦瑶', '郑博文', '王欣怡', '冯子轩', '陈雨萱', '蒋浩宇', '沈静怡',
            '韩志豪', '朱雨桐', '许文博', '何雅婷', '邓俊豪', '苏梦琪', '曹志远', '谢雨欣'
        ];
        
        this.model.clearAllStudents();
        this.model.addStudents(testStudents);
        this.updateViews();
    }
}